package com.bike.service.impl;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bike.entity.HhBusiness;
import com.bike.entity.HhDining;
import com.bike.entity.HhDiningStyle;
import com.bike.mapper.HhBusinessMapper;
import com.bike.mapper.HhDiningMapper;
import com.bike.mapper.HhDiningStyleMapper;
import com.bike.util.Constant;
import com.bike.util.LogoConfig;
import com.bike.util.PageData;
import com.bike.util.TimeManager;
import com.bike.util.Tools;
import com.bike.util.TransFerUtil;
import com.bike.util.UuidUtil;
import com.bike.util.qrcode.ZXingCode;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.google.zxing.BarcodeFormat;
import com.topit.show.aliapi.AlyOssFileUpLoadUtils;

@Service
public class HhDiningServiceImpl extends BaseServcieImpl  {

	@Autowired
	HhDiningMapper hhDiningMapper;
	@Autowired
	HhBusinessMapper hhBusinessMapper;
	@Autowired
	HhDiningStyleMapper hhDiningStyleMapper;
	/**
	* 保存
	*/
	public int saveOrUpdate(HttpServletRequest request,PageData pd, HhDining record) {
		
		if(pd.getLong("diningId")>0){
			 //编辑
			return hhDiningMapper.updateByPrimaryKeySelective(record);
		}else{
			record.setAddTime(TimeManager.currentTime());
			hhDiningMapper.insertSelective(record);
			String realPath = request.getSession().getServletContext().getRealPath("");//项目所在路径
			String alyFileuppath=generateCode( realPath, pd, record);
			if(alyFileuppath==null){
				throw new RuntimeException("生成桌牌失败");
			}
			record.setImg(alyFileuppath);
			// 保存附件信息
			//上传到阿里云
			AlyOssFileUpLoadUtils alyOssFileUpLoadUtils = new AlyOssFileUpLoadUtils();
			alyOssFileUpLoadUtils.fileUpload(alyFileuppath , new File(Constant.filePath+alyFileuppath));//---暂时没有删除本地图片
			return hhDiningMapper.updateByPrimaryKeySelective(record);
		}
		
	}
	
	/**
	* 删除
	*/
	public int deleteHhDiningById(long diningId) {
		return hhDiningMapper.deleteByPrimaryKey(diningId);
	}
	
	/**
	*列表分页
	*/
	public PageData selectHhDiningList(PageData pd) {
		PageData result=new PageData();
		PageBounds pageBounds=(PageBounds) pd.get("pageB");
		String advanceFilter=pd.getString("advanceFilter");
		if(advanceFilter!=null&&!advanceFilter.equals("")){
			advanceFilter=advanceFilter.replaceAll("'", "");
			JSONArray array=JSONObject.parseArray(advanceFilter);
			StringBuffer buffer=new StringBuffer();
			for(int i=0;i<array.size();i++){
				JSONObject object=array.getJSONObject(i);
				String field=object.getString("field");
				String op=object.getString("op");//equal  contains  notequal  greater  greaterorequal  less  lessorequal  beginwith  endwith
				String value=object.getString("value");
				buffer.append(" and ").append(TransFerUtil.getMybatisField(field)).append(TransFerUtil.getMybatisOperation(op,value));
			}
			if(array.size()>0){
				pd.put("condition", buffer.toString());
			}
		}
		List<HhDining> records= hhDiningMapper.selectByPage(pd,pageBounds);
		result.put("rows",records );
		result.put("total", ((PageList<HhDining>) records).getPaginator().getTotalCount());
		return result;
	}
	 
	/**
	*列表(全部)
	*/
	public List<HhDining> listAll(PageData pd) {
		return  hhDiningMapper.selectAll(pd);
	}
	
	/**
	* 通过id获取数据
	*/
	public HhDining selectByHhDiningId(Long diningId) {
		return hhDiningMapper.selectByPrimaryKey(diningId);
	}
	/**
	 * 生成二维码
	 * 
	 * @param data
	 *            桌牌信息
	 * @throws Exception
	 */
	private String generateCode( String realPath,PageData pd,HhDining dining)  {
		String filePath =Constant.filePath;;//本地文件系统
		Long businessId =dining.getBusinessId();// 商家
		Integer diningId = dining.getDiningId();// 桌位ID
		// 生成授权地址
		String jumpUrl = Constant.domain + "/j/" +diningId;
		
		String alyFileuppath =  "qrcode/" + TimeManager.getInstance().getYMD()+ "/".concat(businessId.toString()).concat("/");
		String uuid=UuidUtil.get32UUID();
		
		String outFileName=uuid.concat(Constant.jpg);
		String sourceName="s"+uuid.concat(".").concat(Constant.format);
		
		File outputFile = new File(filePath.concat(alyFileuppath));//本地路径以商家id结尾   桌牌都存在此文件夹下
		 
		if (!outputFile.exists()) {
			outputFile.mkdirs();
		} 
		// 查询商家
		HhBusiness business=hhBusinessMapper.selectByPrimaryKey(businessId);
	
		String logoFilePath=realPath+"/static/images/huhulogo.png";
		String bgFilePath=realPath+"/static/images/bg.jpg";
		
		try {
			ZXingCode.createDining(logoFilePath, jumpUrl, bgFilePath, new File(outputFile,outFileName),new File(outputFile,sourceName),business.getName(),dining.getName());
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		
		return alyFileuppath.concat(outFileName);
	}

	
	public int saveExecDining(String realPath, PageData pd,String diningName) {
		int time=TimeManager.currentTime();
		
		HhDining diningRecord=new HhDining();
		diningRecord.setAddTime(time);
		diningRecord.setBusinessId(pd.getLong("businessId"));
		diningRecord.setName(diningName);
		hhDiningMapper.insertSelective(diningRecord);
		
		String alyFileuppath=generateCode( realPath, pd, diningRecord);
		if(alyFileuppath==null){
			throw new RuntimeException("生成桌牌失败");
		}
		diningRecord.setImg(alyFileuppath);
		// 保存附件信息
		//上传到阿里云
		AlyOssFileUpLoadUtils alyOssFileUpLoadUtils = new AlyOssFileUpLoadUtils();
		alyOssFileUpLoadUtils.fileUpload(alyFileuppath , new File(Constant.filePath+alyFileuppath));//---暂时没有删除本地图片
		hhDiningMapper.updateByPrimaryKeySelective(diningRecord);
		
		return 1;
	}
}

